<template>
	<view>
		<view class="cost-index-head" :style="{height: statusBarHeight +  22,paddingTop: statusBarHeight}">
			<image src="@/static/image/more.png" @click="goToMine" class="icon-title"></image>
			<view class="flex" style="align-items: center;" @click="handlePickerShow">
				<text class="text-20 mr-4">{{ datePicker.year + '-' + datePicker.mon }}</text>
				<!-- <text class="iconfont icon-arrow-down"></text> -->
				<image src="@/static/image/arrowDown.png" style="width: 12px;height: 12px;"></image>
			</view>
			<view class="flex" style="align-items: center;">
				<image src="@/static/image/statistics.png" style="margin-right: 10px;" @click="goToSta"
					class="icon-title"></image>
				<image src="@/static/image/cost.png" @click="goToCost" class="icon-title"></image>
			</view>
		</view>
		<view class="cost-main">
			<image class="cost-main-img" mode="aspectFill" :src="indexImg"></image>
			<view :style="{paddingTop: headEmptyHeight,color:'#fff',paddingLeft: '16px'}">
				<view class="mb-8">
					月支出
				</view>
				<view class="text-24 mb-16">{{formatMoney(res.curMonPay)}}</view>
				<view>
					<text class="mr-10">月收入</text>
					<text class="mr-20">{{formatMoney(res.curMonIn)}}</text>
					<text class="mr-10">本月结余</text>
					<text>{{formatMoney(surplus)}}</text>
				</view>
				<!-- 本月结余 -->
				<!-- <view class="flex" style="justify-content:space-around;" >
					<view class="coast flex-auto flex px-16 pt-24 money" style="align-items: flex-end"
						:style="{color:systemTheme.moneyColor}">
						<text class="text-24 pr-10">¥</text>
						<text class="text-32">{{formatMoney(surplus)}}</text>
					</view>
				
					<view class="flex pr-20" style="align-items: center;color: white;font-weight: bold;"
						@click="openCategoryPopup">
						<text class="text-16">{{ selecteType }}</text>
						<text class="iconfont icon-type text-16" style="padding: 3px;font-weight: normal"></text>
					</view>
				</view> -->
				<!-- 本月收入，支出，剩余预算 -->
				<!-- <view class="income flex" style="color: white;font-weight: bold;padding: 15px 24px 24px 24px">
					<view class="flex flex-column mr-20r basis-1/3" @click="handlePickerShow">
						<text class="text-14 mb-10" style="color: white;">{{ datePicker.year }}年</text>
						<text class="text-22">{{ datePicker.mon }}
							<text class="text-14">月</text>
							<text class="iconfont icon-arrow-down"></text>&nbsp;&nbsp;|
						</text>
					</view>
					<view class="basis-full flex">
						<view class="basis-1/2 flex flex-column">
							<text class="text-14 mb-10">收入</text>
							<text class="text-22">{{formatMoney(res.curMonIn)}}</text>
						</view>
						<view class="basis-1/2 flex flex-column">
							<text class="text-14 mb-10">支出</text>
							<text class="text-22">{{formatMoney(res.curMonPay)}}</text>
						</view>
					</view>
				</view> -->
			</view>

		</view>

		<!-- 本月账单列表 -->
		<view v-if="res.list.length > 0" class="cost-list-content">
			<view class="budget" @click="toBudget">
				<view class="text-18 mb-6">
					预算
				</view>
				<progress class="mb-6" :percent="percent" activeColor="#10AEFF" stroke-width="3" />
				<view class="flex justify-between">
					<text>{{'剩余: ' + formatMoney(residue)}}</text>
					<text>{{'总额: ' + formatMoney(total)}}</text>
				</view>
			</view>
			<view class="flex flex-column p-24r mb-10 bg-white" style="border-radius: 10px;"
				v-for="(item, index) in res.list" :key="index">
				<!-- date week pay in -->
				<view class="flex justify-between">
					<text class="mb-10 text-18">{{ item.date }}
						<text class="text-999 text-14">星期{{ getWeekText(item.date) }}</text>
					</text>
					<view class="text-12">
						<text v-if="getDayInOrPay(item.list).in!=='0.00'">收入: {{ getDayInOrPay(item.list).in }}</text>
						<text class="ml-10" v-if="getDayInOrPay(item.list).pay!=='0.00'"
							:style="{color: systemTheme.infoColor}">支出: {{ getDayInOrPay(item.list).pay }}
						</text>
					</view>
				</view>
				<!-- 当天记录 -->
				<view v-for="(acc,index) in item.list" :key="index" class="detail-item my-10">
					<!-- 左滑 编辑，删除 -->

					<view class="flex items-center px-12" @click="onClick('',acc)">
						<!-- <text v-if="acc.image===''"
								:style="{'background-color': acc.type===1 ? systemTheme.inColor:systemTheme.outColor}"
								style="color: white;font-size: 30px;" class="iconfont p-16r mr-20r rounded-20p"
								:class="acc.icon" />
							<image v-else :src="acc.image" class="w-46p h-46p mr-20r rounded-20p" mode="aspectFill"
								@click="showBigImage(acc.image)" /> -->
						<view class="flex-auto flex flex-column content-start gap-10px">
							<text>{{ acc.title }}</text>
							<!-- <text class="text-12" style="color: #999;">{{ acc.time }}</text> -->
						</view>
						<!-- <text class="flex-auto px-3 text-12"
								style="color: #999;overflow: hidden;  white-space: normal; text-overflow: ellipsis;width: 100px;  display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;">
								{{ acc.remark }}
							</text> -->
						<text :style="{'font-weight':'bold'}">
							<text>{{ acc.type === 0 ? '-' : '+' }}</text>
							{{ formatMoney(acc.num) }}
						</text>
					</view>

				</view>
			</view>
		</view>
		<view v-else class="empty flex-auto flex flex-column justify-center items-center"
			style="height: 200px;align-items: center">
			<text class="iconfont icon-wushuju"></text>
			<text>暂无数据</text>
		</view>
		<!-- 年月选择器 -->
		<KDatePicker v-model="showDatePicker" :defaultValue="datePickerValue" @change="handleConfirm" type="month">
		</KDatePicker>


		<!-- 设置 -->
		<cover-view>
			<uni-popup ref="setPopup" type="bottom" background-color="#fff">
				<view class="flex flex-column">
					<text class="text-center py-24" style="border-bottom: 1px solid #eee;" @click="dataMigration">数据迁移
					</text>
					<text class="text-center py-24">主题</text>
				</view>
			</uni-popup>
		</cover-view>

		<!--    添加账单类型选择-->
		<view>
			<lpyCategorySelect @getValue="changeTypeValue" :value="selecteTypeValue" :themeColor="systemTheme.bg"
				:categoryList="getList" ref="lpyCategorySelect"></lpyCategorySelect>
		</view>
		<!-- 添加悬浮球 -->
		<view class="add-fab" @click="fabClick">
			<uni-icons type="plusempty" color="#fff" size="24"></uni-icons>
		</view>

		<!-- 编辑账单记录 -->
		<setAccount :visible="showPopup" :record="record" :is-update="isUpdateRecord" @close="showPopup=false"
			@updateConfirm="updateRecordConfirm" @delete="deleteItem"></setAccount>
		<image v-show="isShowBigImage" :src="base64Img" mode="aspectFill" class="fixed top-0 left-0 w-100 h-100 z-3"
			@click="isShowBigImage=false" @longpress="saveImage" />
	</view>
</template>

<script>
	import {
		getHome,
		delRecord,
		changeAsset,
		getRank
	} from '@/api/api.js';
	import {
		formatMoney
	} from '@/common/format.js';
	import {
		useTypeStore
	} from '@/store/type';
	import {
		useSystem
	} from "@/store/theme";
	import {
		addRecord,
		updateRecord
	} from '@/api/api.js';
	import KDatePicker from "../../components/k-date-picker/KDatePicker.vue";
	import dayjs from 'dayjs'
	import lpyCategorySelect from "../../components/lpy-category-select/lpy-category-select.vue";

	export default {
		data() {
			return {
				// 悬浮球样式
				fabStyle: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#fff',
					buttonColor: '#fff',
					iconColor: '#fff',
				},
				// 大图
				isShowBigImage: false,
				base64Img: '',
				showDatePicker: false,


				// 日期筛选 时间戳
				datePickerValue: 0,
				percent: 0,
				// 账单数据
				res: {
					curMonPay: 0, //本月支出
					curMonIn: 0, //本月收入
					list: [], //收支明细
				},
				// 滑动操作配置
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}],
				// setAccounts 属性
				record: {},
				showPopup: false,

				// 判断是编辑账单还是新增账单
				isUpdateRecord: false,


				selecteType: '全部类型',
				selecteTypeValue: null,
				indexImg: '',
				headColor: '',
				residue: 0,
				total: 0
			}
		},
		onBackPress(options) {
			if (this.showPopup) {
				this.showPopup = false;
				return true
			}
			return false; // 继续默认的返回行为
		},
		components: {
			KDatePicker,
			lpyCategorySelect
		},
		computed: {
			getList() {
				return this.typeStore.selectTypeList
			},
			//本月结余
			surplus() {
				return this.res.curMonIn - this.res.curMonPay
			},
			datePicker() {
				let date = new Date(this.datePickerValue);
				return {
					year: date.getFullYear(),
					mon: date.getMonth() + 1
				}
			},
			statusBarHeight() {
				return (uni.getSystemInfoSync()).statusBarHeight + 4 + 'px'
			},
			headEmptyHeight() {
				return (uni.getSystemInfoSync()).statusBarHeight + 50 + 'px'
			}
		},

		async onShow() {
			// 重新渲染悬浮球颜色
			this.fabStyle.iconColor = this.systemTheme.bg
			this.fabStyle.selectedColor = this.systemTheme.bg

			// 更新时间
			this.datePickerValue = new Date().getTime()

			// 获取数据
			await this.getData()
			this.indexImg = uni.getStorageSync('INDEX_IMG')
		},

		async onPullDownRefresh() {
			this.datePickerValue = new Date().getTime()
			await this.getData()
			uni.stopPullDownRefresh();
		},
		setup() {
			const typeStore = useTypeStore()
			const systemTheme = useSystem()
			return {
				typeStore,
				systemTheme
			}
		},
		methods: {
			toBudget() {
				uni.navigateTo({
					url: "/pages/budget/budget"
				})
			},
			goToSta() {
				console.log('goToSta')
				uni.navigateTo({
					url: "/pages/chart/index"
				})
			},
			goToMine() {
				uni.navigateTo({
					url: "/pages/mine/index",
					animationType: 'slide-in-left'
				})
			},
			goToCost() {
				uni.navigateTo({
					url: "/pages/asset/index"
				})
			},
			async changeTypeValue(item) {

				if (item !== null) {
					this.selecteTypeValue = item.value
					this.selecteType = item.childKey
				} else {
					this.selecteTypeValue = null
					this.selecteType = '全部类型'
				}
				await this.getData()
				this.$refs.lpyCategorySelect.closePopup()
			},
			openCategoryPopup() {
				this.$refs.lpyCategorySelect.openPopup()
			},
			// 悬浮球点击事件 添加记账
			fabClick() {
				this.isUpdateRecord = false
				this.showPopup = true
			},
			async updateAsset(data) {
				await changeAsset(data);

			},
			async updateRecordConfirm(obj) {

				// 账单结果
				if (this.isUpdateRecord) {
					console.log('updateRecordConfirmobj', obj, this.record)
					await updateRecord(obj)
					await this.getData()
					if (obj.asset_type_id !== this.record.asset_type_id || obj.num !== this.record.num) {
						// 如果跟换了钱包,还原原本的钱包
						await this.updateAsset({
							id: this.record.asset_type_id,
							num: this.record.type === 1 ? -obj.num : obj.num,
						})
						// 更新新钱包
						this.updateAsset({
							id: obj.asset_type_id,
							num: obj.type === 0 ? -obj.num : obj.num,
						})
					}
				} else {
					await addRecord(obj)
					await this.getData()
					this.updateAsset({
						id: obj.asset_type_id,
						num: obj.type === 0 ? -obj.num : obj.num,
					})

				}
				this.showPopup = false
			},
			//左滑操作 编辑/删除
			async deleteItem(obj) {
				const self = this
				uni.showModal({
					title: "删除",
					content: `确认删除[${obj.title}]${obj.type === 0 ? '支出' : '收入'}${obj.remark ? ',[' + obj.remark + ']' : ''}吗?`,
					success: async function(res) {
						if (res.confirm) {
							//todo delete
							await delRecord(obj.id)
							self.showPopup = false
							await self.getData()
							await self.updateAsset({
								id: this.record.asset_type_id,
								num: this.record.type === 1 ? -obj.num : obj.num,
							})
						}
					}
				})
			},
			onClick(e, obj) {
				const self = this
				// 删除
				if (e && e.content.text === '删除') {
					uni.showModal({
						title: "删除",
						content: `确认删除[${obj.title}]${obj.type === 0 ? '支出' : '收入'}${obj.remark ? ',[' + obj.remark + ']' : ''}吗?`,
						success: async function(res) {
							if (res.confirm) {
								//todo delete
								await delRecord(obj.id)
								await self.getData()
								await self.updateAsset({
									id: this.record.asset_type_id,
									num: this.record.type === 1 ? -obj.num : obj.num,
								})
							}
						}
					})
				} else { //编辑
					obj.create_time = this.datePicker.year + '-' + obj.date + ' ' + obj.time
					this.isUpdateRecord = true
					this.record = obj
					this.showPopup = true
				}
			},
			// 显示星期
			getWeekText(mon_date) {
				const weekTxt = ['日', '一', '二', '三', '四', '五', '六']
				const year = this.datePicker.year
				const date = new Date(year + '-' + mon_date)

				return weekTxt[date.getDay()]
			},

			async initData() {
				let budgetList = uni.getStorageSync('budget_list') || []
				if (budgetList.length > 0) {
					let sum = budgetList.reduce((accumulator, currentValue) => {
						return accumulator + currentValue.num;
					}, 0)
					this.total = sum

					const date = new Date()
					const curDay = null;
					const curYear = date.getFullYear().toString()
					const curMon = (date.getMonth() + 1)
					// 本月支出
					const pieChartData = await getRank(0, curYear, curMon, curDay)
					const costMap = new Map()
					pieChartData.map(item => {
						costMap.set(item.type_id, item.num)
					})
					budgetList = budgetList.map(item => {
						let costNum = 0
						if (costMap.has(item.type_id)) {
							costNum = costMap.get(item.type_id)
						}
						return {
							...item,
							costNum: costNum,
							current: costNum / item.num * 100,
							residue: item.num - costNum
						}
					})
					let costTotal = budgetList.reduce((accumulator, currentValue) => {
						return accumulator + currentValue.costNum;
					}, 0)
					this.residue = this.total - costTotal
					this.percent = costTotal / this.total * 100
				}
			},
			async getData() {

				// 使用dayjs来解析时间戳
				let dateFormat = dayjs(this.datePickerValue).format('YYYY-MM');
				this.res = await getHome(dateFormat, this.selecteTypeValue)
				this.initData()
				console.log('获取主页数据', this.res)
			},
			handlePickerShow() {
				this.showDatePicker = true
			},
			// 显示其它日期账单详情
			async handleConfirm(e) {
				if (typeof e === 'number' && !isNaN(e)) {
					this.datePickerValue = e;
					await this.getData()
				}
			},
			handleCancel() {
				this.showDatePicker = false
			},
			formatMoney(num) {
				return formatMoney(num)
			},
			// 获取日收支
			getDayInOrPay(list) {
				const obj = {
					pay: 0,
					in: 0
				}
				for (let item of list) {
					item.type === 1 ? obj.in += item.num : obj.pay += item.num
				}
				obj.pay = formatMoney(obj.pay);
				obj.in = formatMoney(obj.in);
				return obj
			},
			showBigImage(image) {
				this.isShowBigImage = true
				this.base64Img = image
			},
			saveImage() {
				const self = this
				uni.showActionSheet({
					itemList: ['保存到相册'],
					success: function(res) {
						self.saveBaseImgFile()
					},
				})
			},
			// 将base64 图片保存到本地系统相册
			saveBaseImgFile() {
				const self = this
				const bitmap = new plus.nativeObj.Bitmap('base64')
				bitmap.loadBase64Data(this.base64Img, () => {
						const url = '_doc/' + new Date().getTime() + '.png'
						bitmap.save(
							url, {
								overwrite: true // 是否覆盖
								// quality: 'quality'  // 图片清晰度
							},
							(i) => {
								uni.saveImageToPhotosAlbum({
									filePath: url,
									success: () => {
										uni.showToast({
											title: '图片保存成功'
										})
										self.isShowBigImage = false
										bitmap.clear()
									}
								})
							},
							(e) => {
								uni.showToast({
									title: '图片保存失败'
								})
								bitmap.clear()
							}
						)
					},
					(e) => {
						uni.showToast({
							title: '图片保存失败'
						})
						bitmap.clear()
					}
				)
			}

		}
	}
</script>

<style lang="scss">
	.cost-index-head {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: calc(100% - 32px);
		height: 22px;
		text-align: center;
		color: #fff;
		position: fixed;
		z-index: 999;
		padding: 0 16px;
		top: 0;

		.icon-title {
			width: 24px;
			height: 24px;
		}
	}

	.cost-main {
		position: relative;
		width: 100%;
		height: 220px;

		.cost-main-img {
			width: 100%;
			height: 220px;
			background-color: #707070;
			position: absolute;
			top: 0;
			z-index: -99;
		}
	}

	.content {
		display: flex;
		flex-direction: column;
		// justify-content: center;
	}

	.budget {
		margin-bottom: 10px;
		padding: 10px;
		background-color: #fff;
		border-radius: 10px;
	}

	.add-fab {
		position: fixed;
		bottom: 20px;
		left: 50%;
		transform: translateX(-50%);
		background-color: #4f84ff;
		width: 50px;
		height: 50px;
		border-radius: 50%;
		box-shadow: 1px 7px 7px #cbcaca;
		text-align: center;
		line-height: 50px;
	}

	.cost-list-content {
		padding: 10px;
		background-color: #f4f4f4;

	}

	.detail-item {
		padding-bottom: 16px;

		&:last-child {
			margin-bottom: 0;
			border: none;
			padding-bottom: 5px;
		}
	}

	.empty {
		color: #ccc;

		.iconfont {
			font-size: 60px;
			margin-bottom: 10px;
		}
	}

	.money {
		font-size: 25px;
		font-weight: bold;
	}
</style>